<template>
  <view class="chat-container">
    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-top="scrollTop" 
      @scroll="handleScroll"
      :style="{ paddingBottom: '240rpx', height: scrollViewHeight + 'px' }"
      :scroll-with-animation="true"
      :enable-back-to-top="true"
      ref="scrollView"
    >
      <view v-for="(message, index) in messages" :key="index" class="message-item" :class="message.messageType === 'USER' ? 'user-message' : 'assistant-message'">
        <image 
          class="avatar" 
          :src="message.messageType === 'USER' ? '/static/img/user.jpg' : '/static/img/ai.jpg'"
          mode="aspectFill"
        ></image>
        <view class="message-content">
          <text>{{ message.messageType === 'ASSISTANT' ? formatAssistantMessage(message.text) : message.text }}</text>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="isLoading" class="message-item assistant-message">
        <image 
          class="avatar" 
          src="/static/img/ai.jpg"
          mode="aspectFill"
        ></image>
        <view class="message-content loading">
          <text>思考中</text>
          <view class="loading-dots">
            <text class="dot">.</text>
            <text class="dot">.</text>
            <text class="dot">.</text>
          </view>
        </view>
      </view>
      
      <!-- 底部定位元素 -->
      <view id="bottom-anchor" style="height: 1px;"></view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 新聊天按钮 -->
      <view v-if="messages.length > 1" class="new-chat-btn">
        <u-button 
          type="primary" 
          text="+ 新对话" 
          @click="startNewChat"
          :plain="true"
          size="small"
        ></u-button>
      </view>
      <view class="input-wrapper">
        <view class="input-box">
          <textarea
            v-model="inputMessage"
            class="message-input"
            placeholder="请输入您的问题..."
            :disabled="isLoading"
            :auto-height="true"
            :maxlength="-1"
            @confirm="sendMessage"
            :cursor-spacing="20"
            :show-confirm-bar="false"
            :adjust-position="false"
          ></textarea>
          <view class="send-btn-wrapper" :class="{ 'disabled': !inputMessage.trim() || isLoading }">
            <u-button 
              type="primary" 
              text="发送"  
              @click="sendMessage"
              :disabled="!inputMessage.trim() || isLoading"
              size="small"
            ></u-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        messages: [],
        inputMessage: '',
        chatId: '',
        scrollTop: 0,
        baseUrl: 'http://localhost:8000/educational-ai',
        isLoading: false,
        scrollViewHeight: 0,
        autoScroll: true,
        lastScrollTop: 0,
        scrollTimer: null
      }
    },
    onLoad() {
      // 添加欢迎消息
      this.messages.push({
        messageType: 'ASSISTANT',
        text: '嗨~我是客服小团团，有什么问题都可以问我哟~'
      });
      
      // 获取当前学生ID
      this.getStudentId().then(() => {
        // 确保chatId获取成功后再加载聊天历史
        this.loadChatHistory().then(() => {
          this.calculateScrollViewHeight().then(() => {
            this.$nextTick(() => {
              this.scrollToBottom(true);
            });
          });
        });
      });
    },
    onReady() {
      // 页面加载完成后滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    methods: {
      formatAssistantMessage(text) {
        if (!text) return '';
        const parts = text.split('</think>');
        return parts.length > 1 ? parts[1].trim() : text;
      },
      async startNewChat() {
        // 添加确认对话框
        uni.showModal({
          title: '开启新对话',
          content: '开启新对话将清除当前对话记录，是否继续？',
          confirmText: '确定',
          cancelText: '取消',
          success: async (res) => {
            if (res.confirm) {
              // 保留欢迎消息
              const welcomeMessage = this.messages.find(msg => 
                msg.messageType === 'ASSISTANT' && 
                msg.text === '嗨~我是客服小团团，有什么问题都可以问我哟~'
              );
              
              try {
                const response = await uni.request({
                  url: `${this.baseUrl}/ai/newChat`,
                  method: 'GET',
                  data: {
                    chatId: this.chatId
                  }
                });
                
                // 清空消息列表
                this.messages = welcomeMessage ? [welcomeMessage] : [];
                
              } catch (error) {
                console.error('开启新聊天失败:', error);
                uni.$u.toast('开启新聊天失败');
              }
            }
          }
        });
      },
      async loadChatHistory() {
        if(this.chatId === ""){
          uni.$u.toast('请重新登录！');
          return ;
        }
        try {
          // 记录当前滚动高度
          const oldHeight = await this.getScrollHeight();
          
          const response = await uni.request({
            url: `${this.baseUrl}/ai/chatList`,
            method: 'GET',
            data: {
              chatId: this.chatId
            }
          });
          
          if (response.data) {
            // 保存欢迎消息
            const welcomeMessage = this.messages[0];
            // 设置聊天历史
            this.messages = response.data;
            // 如果欢迎消息存在且不在历史记录中，则添加到开头
            if (welcomeMessage && welcomeMessage.messageType === 'ASSISTANT' && 
              !this.messages.some(msg => msg.text === welcomeMessage.text)) {
              this.messages.unshift(welcomeMessage);
            }
            
            // 加载历史消息后保持滚动位置
            this.$nextTick(() => {
              this.keepScrollPosition(oldHeight);
            });
          }
        } catch (error) {
          console.error('加载聊天历史失败:', error);
          uni.$u.toast('加载聊天历史失败');
        }
      },
      async getStudentId(){
        // 使用小程序存储API替代sessionStorage
        const defaultStudentId = '123';
        try {
          // 尝试从存储中获取studentId
          const res = await uni.getStorage({ key: 'studentId' });
          if (res && res.data) {
            this.chatId = res.data;
          } else {
            // 存储中没有则设置默认值
            await uni.setStorage({
              key: 'studentId',
              data: defaultStudentId
            });
            this.chatId = defaultStudentId;
          }
        } catch (error) {
          // 如果获取失败，设置默认值
          await uni.setStorage({
            key: 'studentId',
            data: defaultStudentId
          });
          this.chatId = defaultStudentId;
        }
      },
      
      async sendMessage() {
        if (!this.inputMessage.trim() || this.isLoading) return;
        
        const userMessage = {
          messageType: 'USER',
          text: this.inputMessage
        };
        
        this.messages.push(userMessage);
        // 发送消息后滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom(true);
        });
        
        const prompt = this.inputMessage;
        this.inputMessage = '';
        this.isLoading = true;
        
        try {
          const response = await uni.request({
            url: `${this.baseUrl}/ai/chat`,
            method: 'GET',
            data: {
              prompt: prompt,
              chatId: this.chatId
            },
            timeout: 180000 // 3分钟超时
          });
          
          if (response.data) {
            const assistantMessage = {
              messageType: 'ASSISTANT',
              text: response.data
            };
            this.messages.push(assistantMessage);
            // 接收回复后滚动到底部
            this.$nextTick(() => {
              this.scrollToBottom(true);
            });
          }
        } catch (error) {
          // 判断是否是超时错误
          if (error.errMsg && error.errMsg.includes('timeout')) {
            // 添加提示消息，告知用户AI仍在思考
            this.messages.push({
              messageType: 'ASSISTANT',
              text: '小团团正在努力思考中，请稍等片刻...'
            });
            
            // 启动轮询检查结果
            this.pollForResponse(prompt);
          } else {
            uni.$u.toast('发送消息失败');
          }
        } finally {
          this.isLoading = false;
        }
      },
      
      // 计算滚动区域高度
      calculateScrollViewHeight() {
        return new Promise((resolve) => {
          // 使用同步方式获取系统信息
          const windowInfo = uni.getWindowInfo();
          const query = uni.createSelectorQuery().in(this);
          
          query.select('.input-area').boundingClientRect();
          query.exec(res => {
            if (res[0]) {
              // 窗口高度减去输入区域高度
              this.scrollViewHeight = windowInfo.windowHeight - res[0].height;
              resolve(true);
            } else {
              // 默认值，确保至少有可滚动区域
              this.scrollViewHeight = windowInfo.windowHeight * 0.7;
              resolve(false);
            }
          });
        });
      },
      
      // 获取滚动内容总高度
      getScrollHeight() {
        return new Promise(resolve => {
          const query = uni.createSelectorQuery().in(this);
          query.select('.chat-messages').boundingClientRect();
          query.exec(res => {
            resolve(res[0] ? res[0].height : 0);
          });
        });
      },
      
      // 滚动到底部
      scrollToBottom(force = false) {
        if (!force && !this.autoScroll) return;
        
        clearTimeout(this.scrollTimer);
        this.scrollTimer = setTimeout(() => {
          this.$nextTick(() => {
            const query = uni.createSelectorQuery().in(this);
            query.select('#bottom-anchor').boundingClientRect();
            query.select('.chat-messages').boundingClientRect();
            query.exec(res => {
              if (res[0] && res[1]) {
                // 计算底部锚点距离顶部的距离减去滚动区域高度
                const scrollTop = res[0].top - res[1].top;
                this.scrollTop = scrollTop > 0 ? scrollTop : 0;
              }
            });
          });
        }, 100);
      },
      
      // 保持滚动位置(加载历史消息时)
      keepScrollPosition(oldHeight) {
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this);
          query.select('.chat-messages').boundingClientRect();
          query.exec(res => {
            if (res[0]) {
              const newHeight = res[0].height;
              this.scrollTop = newHeight - oldHeight;
            }
          });
        });
      },
      
      // 滚动事件处理
      handleScroll(e) {
        const { scrollTop, scrollHeight, clientHeight } = e.detail;
        // 判断是否接近底部(1000px范围内)
        this.autoScroll = scrollHeight - (scrollTop + clientHeight) < 1000;
        
        // 记录上次滚动位置
        this.lastScrollTop = scrollTop;
      },
      
      // 轮询检查响应
      pollForResponse(prompt) {
        let attempts = 0;
        const maxAttempts = 10;
        const pollInterval = 3000; // 3秒轮询一次
        
        const poll = () => {
          if (attempts >= maxAttempts) {
            this.messages.push({
              messageType: 'ASSISTANT',
              text: '抱歉，小团团思考时间过长，请稍后再试或重新提问~'
            });
            this.isLoading = false;
            return;
          }
          
          attempts++;
          
          uni.request({
            url: `${this.baseUrl}/ai/checkResponse`,
            method: 'GET',
            data: {
              prompt: prompt,
              chatId: this.chatId
            },
            success: (response) => {
              if (response.data) {
                const assistantMessage = {
                  messageType: 'ASSISTANT',
                  text: response.data
                };
                this.messages.push(assistantMessage);
                this.isLoading = false;
                this.$nextTick(() => {
                  this.scrollToBottom(true);
                });
              } else {
                setTimeout(poll, pollInterval);
              }
            },
            fail: () => {
              setTimeout(poll, pollInterval);
            }
          });
        };
        
        setTimeout(poll, pollInterval);
      }
    },
    watch: {
      messages: {
        deep: true,
        handler(newVal, oldVal) {
          // 只有当是新消息时才自动滚动
          const isNewMessage = newVal.length > oldVal.length;
          this.$nextTick(() => {
            if (isNewMessage) {
              this.scrollToBottom(true);
            }
          });
        }
      }
    }
  }
</script>

<style lang="scss">
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #ffffff;
    position: relative;
  }

  .chat-messages {
    flex: 1;
    padding: 0rpx 5rpx 0 5rpx;
    box-sizing: border-box;
    overflow-anchor: none; /* 防止浏览器自动滚动 */
  }

  .message-item {
    margin-bottom: 30rpx;
    display: flex;
    align-items: flex-start;
    width: 100%;
    padding: 0rpx;
    box-sizing: border-box;
  }

  .message-item:first-child {
    margin-top: 20rpx;
  }

  .message-item:last-child {
    margin-bottom: 40rpx;
  }

  .user-message {
    flex-direction: row-reverse;
  }

  .assistant-message {
    flex-direction: row;
  }

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin: 0 20rpx;
    flex-shrink: 0;
  }

  .message-content {
    width: auto;
    max-width: 60%;
    padding: 20rpx;
    border-radius: 10rpx;
    word-break: break-all;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    position: relative;
    font-size: 30rpx;
    line-height: 44rpx;
    
    &.loading {
      display: flex;
      align-items: center;
    }
  }

  .user-message .message-content {
    background-color: #2979ff;
    color: white;
  }

  .assistant-message .message-content {
    background-color: white;
    color: #333;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1),
          0 -4rpx 8rpx rgba(0, 0, 0, 0.1),
          4rpx 0 8rpx rgba(0, 0, 0, 0.1),
          -4rpx 0 8rpx rgba(0, 0, 0, 0.1);
  }

  .loading-dots {
    display: flex;
    margin-left: 4rpx;
    
    .dot {
      animation: dotAnimation 1.4s infinite;
      opacity: 0;
      
      &:nth-child(2) {
        animation-delay: 0.2s;
      }
      
      &:nth-child(3) {
        animation-delay: 0.4s;
      }
    }
  }

  @keyframes dotAnimation {
    0%, 20% {
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }

  .new-chat-btn {
    display: flex;
    justify-content: center;
    margin-bottom: 16rpx;
    
    :deep(.u-button) {
      width: 160rpx !important;
      height: 56rpx !important;
      font-size: 24rpx !important;
      border-radius: 28rpx !important;
    }
  }

  .input-area {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    border-top: 1rpx solid #eaeaea;
    padding: 0rpx 20rpx;
    box-sizing: border-box;
    z-index: 100;
    // padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(0rpx + env(safe-area-inset-bottom));
  }

  .input-wrapper {
    width: 100%;
  }

  .input-box {
    display: flex;
    align-items: flex-end;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 16rpx 20rpx;
    box-sizing: border-box;
    border: 2rpx solid #e5e5e5;
    min-height: 80rpx;
  }

  .message-input {
    flex: 1;
    min-height: 60rpx;
    max-height: 200rpx;
    font-size: 30rpx;
    line-height: 44rpx;
    width: 0;
    background: transparent;
    padding: 0;
  }

  .send-btn-wrapper {
    margin-left: 16rpx;
    display: flex;
    align-items: flex-end;
    
    &.disabled {
      opacity: 0.5;
    }
    
    :deep(.u-button) {
      width: 140rpx !important;
      height: 80rpx !important;
      font-size: 30rpx !important;
      border-radius: 40rpx !important;
      margin: 0 !important;
    }
  }
</style>